//阿里云-电力市场
//var SERVER_ADDRESS = "http://lvjing.site:8011/snjk"; //开发地质

var SERVER_ADDRESS = "http://192.168.2.172:8080/snjk"; //开发地质
//var SERVER_ADDRESS = "http://192.168.2.156:8080/snjk"; //开发地质

/**
 * 设置和获取token
 */
function getToken() {
	return localStorage.getItem("access_token");
}

function setToken(value) {
	localStorage.setItem("access_token", value);
}

/**
 *设置用户名
 * @param {Object} value
 */
function setAccount(value) {
	localStorage.setItem('account', JSON.stringify(value));
};

function setSHB(SHB) {
	localStorage.setItem('shb', JSON.stringify(SHB));
}

function getSHB() {
	var account = localStorage.getItem('shb');
	return JSON.parse(account);
}
/**
 * 获取用户名
 *  @return isAutoLogin
 */
function getAccount() {
	var account = localStorage.getItem('account');
	return JSON.parse(account);
};

/*
 * 设置和获取弹出框的值，默人是数组
 * 
 */

/**
 * 获取定位元素，最大的z-index  
 */
function getMaxZIndex(dom, excludeDoms) {
	excludeDoms = Array.isArray(excludeDoms) ? excludeDoms : [excludeDoms];
	dom = dom || document.body;
	var maxZindex = -1;
	var items = dom.querySelectorAll('*');
	for(var i = 0, len = items.length; i < len; i++) {
		var item = items[i];
		if(excludeDoms.indexOf(item) > -1) {
			continue;
		}
		var styles = getComputedStyle(item);
		if(styles['position'] !== 'static') {
			var zIndex = styles["zIndex"];
			var getIt = zIndex != 'auto';
			if(getIt) {
				if(parseInt(zIndex) > maxZindex) {
					maxZindex = parseInt(zIndex);
				}
			}
		}
	}
	return maxZindex;
}

/**
 * 函数防抖
 * @param {Object} fn
 * @param {Object} delay
 * @param {Object} immediately 是否立即执行
 * @param {Object} scope 
 */
function debounce(fn, delay, immediately, scope) {
	var timer = null;
	// 返回函数对debounce作用域形成闭包
	return function() {
		// setTimeout()中用到函数环境总是window,故需要当前环境的副本；
		var context = scope || this,
			args = arguments;
		if(immediately) {
			var callNow = !timer;
			timer = setTimeout(function() {
				timer = null;
			}, delay);
			if(callNow) {
				fn.apply(context, args);
			}
		} else {
			// 如果事件被触发，清除timer并重新开始计时
			clearTimeout(timer);
			timer = setTimeout(function() {
				fn.apply(context, args);
			}, delay);
		}
	}
}

/**
 * 函数节流
 * @param {Object} fn
 * @param {Object} threshold
 * @param {Object} scope
 */
function throttle(fn, threshold, scope) {
	var timer;
	var prev = Date.now();
	return function() {
		var context = scope || this,
			args = arguments;
		var now = Date.now();
		if(now - prev > threshold) {
			prev = now;
			fn.apply(context, args);
		}
	}
}

function AntiSqlValid(p_val) {
	re = /update\s+|delete\s+|exec\s+|;|(\*)|(\*\/)|(--)/i;
	if(re.test(p_val)) {
		//alert("请您不要在参数中输入特殊字符和SQL关键字！"); //注意中文乱码		
		return false;
	}

	return true;
}
/**
 * 判断数组中是否存在指定元素
 * @param {Object} array
 * @param {Object} ele
 */
function eleInArray(array, ele) {
	var length = array.length;
	for(var i = 0; i < length; i++) {
		if(ele === array[i])
			return true;
	}
	return false;
}

/**
 * 将ele从array中删除
 * @param {Object} array
 * @param {Object} ele
 */
function removeEleFromArray(array, ele) {
	var length = array.length;
	for(var i = 0; i < length; i++) {
		if(ele === array[i]) {
			for(var j = i + 1; j < length; j++) {
				array[j - 1] = array[j];
			}
			array.pop();
		}
	}

	return array;
}

/**
 * 获取json的元素数目
 * @param {Object} obj
 */
function JSONLength(obj) {
	var size = 0,
		key;
	for(key in obj) {
		if(obj.hasOwnProperty(key)) size++;
	}
	return size;
};

/**
 * 检查是否为有效字符串
 * @param {Object} str
 */
function isNullorEmptyorUndefined(str) {
	if(str == null || str == "" || str == undefined || str == "undefined")
		return true;
	else
		return false;
}
//rem转换px函数
function remToPx(val) {
	val = val || 0;
	var windowWidth = window.screen.availWidth || window.clientWidth || window.innerWidth;
	if(windowWidth > 500) {
		return windowWidth / 7.2 / 1.5 * val
	} else {
		return windowWidth / 7.2 * val
	}
}

/**
 * 获取定位元素，最大的z-index  
 */
function getMaxZIndexDom(dom, excludeDoms) {
	excludeDoms = Array.isArray(excludeDoms) ? excludeDoms : [excludeDoms];
	dom = dom || document.body;
	var maxDom = dom;
	var maxZindex = -1;
	var items = dom.querySelectorAll('*');
	for(var i = 0, len = items.length; i < len; i++) {
		var item = items[i];
		if(excludeDoms.indexOf(item) > -1) {
			continue;
		}
		var styles = getComputedStyle(item);
		if(styles['position'] !== 'static') {
			var zIndex = styles["zIndex"];
			var getIt = zIndex != 'auto';
			if(getIt) {
				if(parseInt(zIndex) > maxZindex) {
					maxZindex = parseInt(zIndex);
					maxDom = item;
				}
			}
		}
	}
	return maxDom;
}

function getTck() {
	var tempdata = [{
		text: '其他',
		value: '2001401'
	}, {
		text: '人员不足，请转派其他班组',
		value: '2001402'
	}, {
		text: '故障地点在抢修范围外',
		value: '2001403'
	}];
	//localStorage.setItem("setTck", JSON.stringify(tempdata));

	if(localStorage.getItem("setTck")) {
		return JSON.parse(localStorage.getItem("setTck"));
	}
	return tempdata;
}

function setTck(value) {
	localStorage.setItem("setTck", JSON.stringify(value));
}

var JUMP_DURATION_TIME = 300;
var ISLOG = true;
// 用于登录的ajax
function ajax(url, params, cbSuccess, cbError) {
	if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
		plus.nativeUI.closeWaiting();
		mui.toast('当前网络不给力');
		cbError && cbError();
		return;
	}
	params.agent = 2;
	params.sendByAngent = true;
	var str = JSON.stringify(params.params);
	params.params = str;
	console.log('请求地址' + SERVER_ADDRESS + url + '---params: ' + JSON.stringify(params));
	mui.ajax(SERVER_ADDRESS + url, {
		data: params,
		type: 'post',
		timeout: 20000,
		success: function(data) {
			console.log('请求地址' + url + '---返回data: ' + data);
			plus.nativeUI.closeWaiting();
			data = isJson(data) ? data : JSON.parse(data || '{}');
			cbSuccess(data);
		},
		error: function(xhr, type, errorThrown) {
			plus.nativeUI.closeWaiting();
			switch(type) {
				case 'timeout':
					console.log("请求超时");
					break;
				case 'error':
					console.log("请求错误,无法找到文件");
					break;
				case 'abort':
					console.log("请求中断");
					break;
				case 'parsererror':
					console.log("数据解析错误");
					break;
				case 'null':
					console.log("未知错误");
					console.log('异常对象为' + errorThrown);
					break
			}
			if(xhr.status === 601 || xhr.status === 606) { //601session超时，606请求
				mui.toast(xhr.responseText);
				mui.later(function() {
					var self = plus.webview.currentWebview();
					var allWebview = plus.webview.all();
					allWebview.forEach(function(item, index) {
						if(item.id == self.id || item.id == plus.webview.getLaunchWebview().id || (self.parent() && item.id == self.parent().id)) {

						} else {
							item.hide();
							item.close("none");
						}
					})
					if(self.id !== plus.webview.getLaunchWebview().id) {
						mui.later(function() {
							if(self.parent()) {
								self.parent().close();
							} else {
								self.close();
							}

						}, 300)
					}
				}, 2000)
			} else {
				mui.toast("请求失败")
			}
			//			if(cbError != undefined) {
			//				cbError();
			//			}
		}
	});
};

function ajaxF1(url, params, cbSuccess, cbError) {
	if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
		plus.nativeUI.closeWaiting();
		mui.toast('当前网络不给力');
		cbError && cbError();
		return;
	}
	var paramss = {};
	paramss.sendByAngent = 'true';
	paramss.param = JSON.stringify(params);
	paramss.agent = 2;
	mui.ajax(SERVER_ADDRESS + url, {
		data: paramss,
		type: 'post',
		timeout: 20000,
		success: function(data) {
			//			console.log('请求地址' + SERVER_ADDRESS + url + '---返回data: ' + data);
			data = isJson(data) ? data : JSON.parse(data || '{}');
			cbSuccess(data);
		},
		error: function(xhr, type, errorThrown) {
			plus.nativeUI.closeWaiting();
			switch(type) {
				case 'timeout':
					console.log("请求超时");
					break;
				case 'error':
					console.log("请求错误,无法找到文件");
					break;
				case 'abort':
					console.log("请求中断");
					break;
				case 'parsererror':
					console.log("数据解析错误");
					break;
				case 'null':
					console.log("未知错误");
					console.log('异常对象为' + errorThrown);
					break
			}

			if(cbError != undefined) {
				cbError();
			}
		}
	});
};

/*
 * 用于云台控制代码
 */
function ajaxF2(url, params, cbSuccess, cbError) {
	if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
		plus.nativeUI.closeWaiting();
		mui.toast('当前网络不给力');
		cbError && cbError();
		return;
	}
	mui.ajax(url, {
		data: params,
		type: 'post',
		timeout: 20000,
		success: function(data) {
			console.log('请求地址' + SERVER_ADDRESS + url + '---返回data: ' + data);
			data = isJson(data) ? data : JSON.parse(data || '{}');
			cbSuccess(data);
		},
		error: function(xhr, type, errorThrown) {
			plus.nativeUI.closeWaiting();
			switch(type) {
				case 'timeout':
					console.log("请求超时");
					break;
				case 'error':
					console.log("请求错误,无法找到文件");
					break;
				case 'abort':
					console.log("请求中断");
					break;
				case 'parsererror':
					console.log("数据解析错误");
					break;
				case 'null':
					console.log("未知错误");
					console.log('异常对象为' + errorThrown);
					break
			}

			if(cbError != undefined) {
				cbError();
			}
		}
	});
};

/**
 *  获取公共代码
 * @param {Object} label_code
 */
function getCommonCode(label_code, callback) {
	var resultValue;
	var url = "/ydgapp/common/commonCode.do";
	var params = {
		persId: plus.storage.getItem('persId'),
		label_code: label_code
	};
	ajax(url, params, function(data) {
		if(data) {
			if(data.successful) {

				resultValue = data.resultValue;

			} else {
				//				mui.toast(data.resultHint);
				resultValue = [];
			}
		};
		callback(resultValue);
	}, function(xhr, type, errorThrown) { //出现异常
		//		mui.toast('异常信息 :' + type + ' ' + errorThrown);
		resultValue = [];
	});

};
/**
 *设置userModel
 *  "persId": "0AA4BFD9-C9F9-4051-A311-619253A1DD45-00300",
    "persGuid": "ff808081487cf4a90148817bc49b0305",
    "persName": "张松",
    "loginId": "13333331111",
    "loginPass ": "123456",
    "deptName": "北京中恒博瑞数字电力科技有限公司",
    "deptId": "123456789",
    "sex": "男",
    "telephone": "01082827680",
    "mobilephone": "13333331111",
    "email": "6thman@163.com"

 * @param {Object} userModel
 */
function setUserModel(userModel) {
	plus.storage.setItem(USER_MODEL, JSON.stringify(userModel));
};
/**
 * 获取usermodel
 * @return userModel
 */
function getUserModel() {
	var userModel = plus.storage.getItem('userModel');
	return JSON.parse(userModel);
}
/**
 *清除UserModel
 */
function removeUserModel() {
	plus.storage.removeItem('userModel');
};

function setUserID(id) {
	plus.storage.setItem(USER_ID, id);
}

function getUserID() {
	return plus.storage.getItem(USER_ID);
}

function setAutoLogin(isAutologin) {
	plus.storage.setItem("isAutologin", isAutologin || "false");
}

function getAutoLogin() {
	return plus.storage.getItem("isAutologin");
}

/**
 * 保存设备列表
 * @param {Object} deviceList
 */
function saveDeviceList(deviceList) {
	plus.storage.setItem(DEVICE_LIST, JSON.stringify(deviceList));
}

/**
 * 获取设备列表
 */
function getDeviceList() {
	var deviceList = plus.storage.getItem(DEVICE_LIST);
	return JSON.parse(deviceList);
}
/**
 * 移除设备列表
 */
function removeDeviceList() {
	plus.storage.removeItem(DEVICE_LIST);
}

function setDeviceNum(num) {
	plus.storage.setItem(DEVICE_NUM, num + "");
}

function getDeviceNum() {
	var deviceNum = plus.storage.getItem(DEVICE_NUM);
	return deviceNum ? parseInt(deviceNum) : 1;
}

function removeDeviceNum() {
	//	plus.storage.removeItem(DEVICE_NUM);
	plus.storage.setItem(DEVICE_NUM, 1);
}

function setUnreadMsgNum(num) {
	plus.storage.setItem(UNREAD_MSG_NUM, num + "");
}

function getUnreadMsgNum() {
	var num = plus.storage.getItem(UNREAD_MSG_NUM);
	return num ? (parseInt(num) == NaN ? 0 : parseInt(num)) : 0;
}
/**
 *设置服务地址
 * @param {Object} value
 */
function setServiceAddress(value) {
	localStorage.setItem('serviceAddress', JSON.stringify(value));
};
/**
 *设置密码
 * @param {Object} value
 */
function setPassword(value) {
	localStorage.setItem('password', JSON.stringify(value));
};

/**
 * 获取密码
 *  @return password
 */
function getPassword() {
	var password = localStorage.getItem('password');
	return JSON.parse(password);
};
/**
 * 获取服务地址
 *  @return serviceAddress
 */
function getServiceAddress() {
	var value = localStorage.getItem('serviceAddress');
	if(value) {
		return JSON.parse(value);
	} else {
		return serverAddress;
	}
};

//检查obi是否为json格式
function isJson(obj) {
	var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
	return isjson;
}

/**
 * 检查手机号格式
 * @param {Object} phone
 */
function isMobilePhone(phone) {
	var myreg = /^1[0-9]{10}$/;
	return myreg.test(phone);
}

/**
 * 检查邮箱格式
 */
function isEmailAddress(email) {
	var myreg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
	return myreg.test(email);
}

/**
 * 从JSONArray中删除指定元素
 */
function removeFromJSONArray(jsonarray, key, value) {
	var result = [];
	//console.log("jsonarray = " + JSON.stringify(jsonarray));
	if(jsonarray && jsonarray.length >= 1) {
		//console.log("value = " + value);
		var length = jsonarray.length;
		for(var i = 0; i < length; i++) {
			if(jsonarray[i][key] != value)
				result.push(jsonarray[i]);
		}
		return result;
	} else {
		//console.log("json格式错误");
		return jsonarray;
	}
}

/**
 * 计算数组的和
 * @param {Object} array
 */
function calArraySum(array) {
	var sum = 0;
	var length = array.length;
	for(var i = 0; i < length; i++) {
		sum += parseInt(array[i]);
	}
	return sum;
}
/**
 * "fade-in": (String 类型 )从透明到不透明逐渐显示效果页面从完全透明到不透明逐渐显示。 对应关闭动画"fade-out"。
 */
var jumpOptionFadein = {
	//	preload: true,
	show: {
		aniShow: 'fade-in',
		duration: "300"
	},
	styles: {
		popGesture: 'hide'
	},
	waiting: {
		autoShow: false
	}
};
/**
 * "pop-in": (String 类型 )从右侧平移入栈动画效果页面从屏幕右侧滑入显示，同时上一个页面带阴影效果从屏幕左侧滑出隐藏。 对应关闭动画"pop-out"。
 */
var jumpOptionPopin = {
	//	preload: true,
	show: {
		aniShow: 'pop-in',
		duration: "300"
	},
	styles: {
		popGesture: 'hide'
	},
	waiting: {
		autoShow: false
	}
};
/**
 *  "slide-in-left": (String 类型 )从左侧横向滑动效果
 */
var jumpOptionSlideInL = {
	//	preload: true,
	show: {
		aniShow: 'slide-in-left',
		duration: "300"
	},
	styles: {
		popGesture: 'hide'
	},
	waiting: {
		autoShow: false
	}
};

/**
 *"slide-in-right": (String 类型 )从右侧横向滑动效果
 */
var jumpOptionSlideInR = {
	//	preload: true,
	show: {
		aniShow: 'slide-in-right',
		duration: "300"
	},
	styles: {
		popGesture: 'hide'
	},
	waiting: {
		autoShow: false
	}
};

/**
 * "slide-in-bottom": (String 类型 )从下侧竖向滑动效果,	页面从屏幕下侧向上竖向滑动显示。 对应关闭动画"slide-out-bottom"
 */
var jumpOptionSlideInBottom = {
	//	preload: true,
	show: {
		aniShow: 'slide-in-bottom',
		duration: "300"
	},
	styles: {
		popGesture: 'hide'
	},
	waiting: {
		autoShow: false
	}
};

/**
 * "slide-in-top": (String 类型 )从上侧竖向滑动效果,页面从屏幕上侧向下竖向滑动显示。 对应关闭动画"slide-out-top"
 */
var jumpOptionSlideInTop = {
	//	preload: true,
	show: {
		aniShow: 'slide-in-top',
		duration: "300"
	},
	styles: {
		popGesture: 'hide'
	},
	waiting: {
		autoShow: false
	}
};

/**
 * "zoom-out": (String 类型 )从小到大逐渐放大显示效果页面在屏幕中间从小到大逐渐放大显示。 对应关闭动画"zoom-in"。
 */
var jumpOptionZoomOut = {
	//	preload: true,
	show: {
		aniShow: 'zoom-out',
		duration: "300"
	},
	styles: {
		popGesture: 'hide'
	},
	waiting: {
		autoShow: false
	}
};
/**
 * ""zoom-fade-out": (String 类型 )从小到大逐渐放大并且从透明到不透明逐渐显示效果页面在屏幕中间从小到大逐渐放大并且从透明到不透明逐渐显示。 对应关闭动画"zoom-fade-in"。
 */
var jumpOptionZoomFadeOut = {
	//	preload: true,
	show: {
		aniShow: 'zoom-fade-out',
		duration: "300"
	},
	styles: {
		popGesture: 'hide'
	},
	waiting: {
		autoShow: false
	}
};

/**
 * 
 * @param {Object} url
 * @param {Object} id
 * @param {Object} option
 * @param {Object} extras
 */
function jumpTo(url, id, option, extras) {
	url = url.lastIndexOf(".html") >= 0 ? url : url + ".html";
	mui.openWindow({
		url: url,
		id: id,
		//		styles:{
		//			statusbar:
		//		},
		show: option,
		extras: extras || {},
		waiting: {
			autoShow: false
		}
	});
	document.activeElement.blur();
}

/**
 *"slide-in-right": (String 类型 )从右侧横向滑动效果
 */
var jumpSlideInRight = {
	aniShow: 'slide-in-right',
	duration: JUMP_DURATION_TIME
};
/**
 * "fade-in": (String 类型 )从透明到不透明逐渐显示效果页面从完全透明到不透明逐渐显示。 对应关闭动画"fade-out"。
 */
var jumpFadeIn = {
	aniShow: 'fade-in',
	duration: JUMP_DURATION_TIME
};

/**
 * "pop-in": (String 类型 )从右侧平移入栈动画效果页面从屏幕右侧滑入显示，同时上一个页面带阴影效果从屏幕左侧滑出隐藏。 对应关闭动画"pop-out"。
 */
var jumpPopIn = {
	aniShow: 'pop-in',
	duration: JUMP_DURATION_TIME
};

/**
 *  "slide-in-left": (String 类型 )从左侧横向滑动效果
 */
var jumpSlideInLeft = {
	aniShow: 'slide-in-left',
	duration: JUMP_DURATION_TIME
};
/**
 * ""zoom-fade-out": (String 类型 )从小到大逐渐放大并且从透明到不透明逐渐显示效果页面在屏幕中间从小到大逐渐放大并且从透明到不透明逐渐显示。 对应关闭动画"zoom-fade-in"。
 */
var jumpZoomFadeOut = {
	aniShow: 'zoom-fade-out',
	duration: JUMP_DURATION_TIME
};
/**
 * "zoom-out": (String 类型 )从小到大逐渐放大显示效果页面在屏幕中间从小到大逐渐放大显示。 对应关闭动画"zoom-in"。
 */
var jumpZoomOut = {
	aniShow: 'zoom-out',
	duration: JUMP_DURATION_TIME
};

/**
 * "slide-in-top": (String 类型 )从上侧竖向滑动效果,页面从屏幕上侧向下竖向滑动显示。 对应关闭动画"slide-out-top"
 */
var jumpSlideInTop = {
	aniShow: 'slide-in-top',
	duration: JUMP_DURATION_TIME
};
/**
 * "slide-in-bottom": (String 类型 )从下侧竖向滑动效果,	页面从屏幕下侧向上竖向滑动显示。 对应关闭动画"slide-out-bottom"
 */
var jumpSlideInBottom = {
	aniShow: 'slide-in-bottom',
	duration: JUMP_DURATION_TIME
};
/**
 * 跳转至指定页面，自定义id
 * @param {Object} url
 * @param {Object} id
 * @param {Object} option
 * @param {Object} extras
 */
function jumpToWithId(url, id, option, extras) {
	//	url = url.lastIndexOf(".html") >= 0 ? url : url + ".html";
	//	mui.openWindow({
	//		url: url,
	//		id: id,
	//		show: option,
	//		extras: extras || {},
	//		waiting: {
	//			autoShow: false
	//		}
	//	});
	//	document.activeElement.blur();
	jumpTo(url, id, option, extras);
}
//rem转换px函数
function remToPx(val) {
	val = val || 0;
	var windowWidth = window.screen.availWidth || window.clientWidth || window.innerWidth;
	if(windowWidth > 500) {
		return windowWidth / 7.2 / 1.5 * val
	} else {
		return windowWidth / 7.2 * val
	}
}
/**
 * 跳转至登录页面
 */
function jumpToLogin() {
	var appid = plus.runtime.appid;
	jumpTo("_www/module/login/login.html", "login.html", jumpPopIn)
}
/**
 * 检查是否为有效字符串
 * @param {Object} str
 */
function isNullorEmptyorUndefined(str) {
	if(str == null || str == "" || str == undefined || str == "undefined")
		return true;
	else
		return false;
}

/**
 * 获取json的元素数目
 * @param {Object} obj
 */
function JSONLength(obj) {
	var size = 0,
		key;
	for(key in obj) {
		if(obj.hasOwnProperty(key)) size++;
	}
	return size;
};

/**
 * 将ele从array中删除
 * @param {Object} array
 * @param {Object} ele
 */
function removeEleFromArray(array, ele) {
	var length = array.length;
	for(var i = 0; i < length; i++) {
		if(ele === array[i]) {
			for(var j = i + 1; j < length; j++) {
				array[j - 1] = array[j];
			}
			array.pop();
		}
	}

	return array;
}

/**
 * 判断数组中是否存在指定元素
 * @param {Object} array
 * @param {Object} ele
 */
function eleInArray(array, ele) {
	var length = array.length;
	for(var i = 0; i < length; i++) {
		if(ele === array[i])
			return true;
	}
	return false;
}

function setLocal(p_key, p_val) {
	//	localStorage.setItem(p_key, p_val);
	localStorage.setItem(p_key, JSON.stringify(p_val));
}

function getLocal(p_key) {
	var val = localStorage.getItem(p_key);
	return JSON.parse(val);
}
/**
 * id选择器
 * @param {Object} id
 * @return {Object} 返回第一个id的元素
 */
function f1SelectId(id) {
	var ele = mui("#" + id + "")[0];
	if(ele) {
		return ele;
	} else {
		return document.getElementById(id);
	}
}

var commonJsBridgeService;
document.addEventListener("plusready", function() {
	//	window.activity = plus.android.runtimeMainActivity();
	// 定义js桥服务
	commonJsBridgeService = {
		execAsync: function(service, action, Argus, successCallback,
			errorCallback) {
			var success = typeof successCallback !== 'function' ? null :
				function(args) {
					successCallback(args);
				},
				fail = typeof errorCallback !== 'function' ? null :
				function(code) {
					errorCallback(code);
				};
			callbackID = window.plus.bridge.callbackId(success, fail);
			return window.plus.bridge.exec(service, action, [callbackID, Argus]);
		},
		execSync: function(service, action, args) {
			return window.plus.bridge.execSync(service, action, [args]);
		}
	};
	window.plus.commonJsBridgeService = commonJsBridgeService;
	//定义推送接收
});

/**
 * 函数防抖
 * @param {Object} fn
 * @param {Object} delay
 * @param {Object} immediately 是否立即执行
 * @param {Object} scope 
 */
function debounce(fn, delay, immediately, scope) {
	var timer = null;
	// 返回函数对debounce作用域形成闭包
	return function() {
		// setTimeout()中用到函数环境总是window,故需要当前环境的副本；
		var context = scope || this,
			args = arguments;
		if(immediately) {
			var callNow = !timer;
			timer = setTimeout(function() {
				timer = null;
			}, delay);
			if(callNow) {
				fn.apply(context, args);
			}
		} else {
			// 如果事件被触发，清除timer并重新开始计时
			clearTimeout(timer);
			timer = setTimeout(function() {
				fn.apply(context, args);
			}, delay);
		}
	}
}

/**
 * 函数节流
 * @param {Object} fn
 * @param {Object} threshold
 * @param {Object} scope
 */
function throttle(fn, threshold, scope) {
	var timer;
	var prev = Date.now();
	return function() {
		var context = scope || this,
			args = arguments;
		var now = Date.now();
		if(now - prev > threshold) {
			prev = now;
			fn.apply(context, args);
		}
	}
}

function AntiSqlValid(p_val) {
	re = /update\s+|delete\s+|exec\s+|;|(\*)|(\*\/)|(--)/i;
	if(re.test(p_val)) {
		//alert("请您不要在参数中输入特殊字符和SQL关键字！"); //注意中文乱码		
		return false;
	}

	return true;
}

/**
 * 获取定位元素，最大的z-index  
 */
function getMaxZIndexDom(dom, excludeDoms) {
	excludeDoms = Array.isArray(excludeDoms) ? excludeDoms : [excludeDoms];
	dom = dom || document.body;
	var maxDom = dom;
	var maxZindex = -1;
	var items = dom.querySelectorAll('*');
	for(var i = 0, len = items.length; i < len; i++) {
		var item = items[i];
		if(excludeDoms.indexOf(item) > -1) {
			continue;
		}
		var styles = getComputedStyle(item);
		if(styles['position'] !== 'static') {
			var zIndex = styles["zIndex"];
			var getIt = zIndex != 'auto';
			if(getIt) {
				if(parseInt(zIndex) > maxZindex) {
					maxZindex = parseInt(zIndex);
					maxDom = item;
				}
			}
		}
	}
	return maxDom;
}
/**
 * 获取定位元素，最大的z-index  
 */
function getMaxZIndex(dom, excludeDoms) {
	excludeDoms = Array.isArray(excludeDoms) ? excludeDoms : [excludeDoms];
	dom = dom || document.body;
	var maxZindex = -1;
	var items = dom.querySelectorAll('*');
	for(var i = 0, len = items.length; i < len; i++) {
		var item = items[i];
		if(excludeDoms.indexOf(item) > -1) {
			continue;
		}
		var styles = getComputedStyle(item);
		if(styles['position'] !== 'static') {
			var zIndex = styles["zIndex"];
			var getIt = zIndex != 'auto';
			if(getIt) {
				if(parseInt(zIndex) > maxZindex) {
					maxZindex = parseInt(zIndex);
				}
			}
		}
	}
	return maxZindex;
}
// 命名空间
function $namespace(p_namespace) {
	var parts = p_namespace.split(".");
	if(parts.length == 0) {
		return null;
	}

	// 命名空间的第一层一定是一个 Weblet，如果没有则必须使用 WebletManager.load 加载。
	var webletName = parts[0];
	try {
		eval("(" + webletName + ")");
	} catch(e) {
		//      throw new Error("$ns:" + webletName);
		eval(webletName + " = {};");
	}

	var space = parts[0];
	for(var i = 1; i < parts.length; i++) {
		space += "." + parts[i];
		if(!eval(space)) {
			eval(space + " = {};");
		}
	}
	return eval(p_namespace);
}
$ns = $namespace;

function rountStreet(JD, WD, LXDZ) {
	//弹出下拉选择框
	if(mui("#div_popover")[0]) {
		mui("#div_popover").popover("toggle");
	} else {
		var str = '<ul class="mui-table-view">' +
			'<li class="mui-table-view-cell rount" ><a>高德地图</a></li>' +
			'<li class="mui-table-view-cell rount" ><a>百度地图</a></li>' +
			'</ul>' +
			'<ul class="mui-table-view">' +
			'<li class="mui-table-view-cell rount" ><a>取消</a></li>' +
			'</ul>';
		var _popover = document.createElement("div");
		_popover.id = "div_popover";
		_popover.className = "mui-popover mui-popover-action mui-popover-bottom";
		_popover.innerHTML = str;
		mui("body")[0].appendChild(_popover);
		mui("#div_popover").popover("toggle");
		//底部弹出框
		mui("#div_popover").on("tap", "a", function(e) {
			mui("#div_popover").popover("toggle");
			if(text != '取消') {
				var result = commonJsBridgeService.execSync("commonJsBridgeService", "JudgeDT", {
					'type': text,
					'JD': JD,
					'WD': WD,
					'locationname': LXDZ
				});
				if(result && result.result.success) {
					return;
				} else {
					mui.toast("请安装" + text);
				}
			}

		});
	}

}

function getSjc(date1, date2) {
	var date3 = new Date(date2).getTime() - new Date(date1).getTime(); //时间差的毫秒数      
	if(date3 <= 0) {
		return 0 + "分钟";
	} else {
		//计算出相差天数
		var days = Math.floor(date3 / (24 * 3600 * 1000))

		//计算出小时数

		var leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
		var hours = Math.floor(leave1 / (3600 * 1000))
		//计算相差分钟数
		var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
		var minutes = Math.floor(leave2 / (60 * 1000))
		if(days > 0) {
			return days + "天 " + hours + "小时 " + minutes + " 分钟";
		} else if(hours > 0) {
			return hours + "小时 " + minutes + " 分钟";
		} else {
			return minutes + " 分钟";
		}
	}

}